package com.example.controller;

import com.example.dao.UserDAO;
import com.example.model.SystemAdmin;
import com.example.model.ManagementUser;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    private UserDAO userDAO = new UserDAO();

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置请求和响应的编码格式为UTF-8
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String role = request.getParameter("role");

        switch (role) {
            case "系统管理员":
                System.out.println("进入系统管理员登录运行功能！");
                SystemAdmin admin = userDAO.loginSystemAdmin(username, password);
                if (admin != null) {
                    System.out.println("进入系统管理员判断功能");
                    HttpSession session = request.getSession();
                    session.setAttribute("admin", admin);
                    response.sendRedirect("admin/index.jsp");
                } else {
                    request.setAttribute("error", "用户名或密码错误");
                    request.getRequestDispatcher("jsp/login.jsp").forward(request, response);
                }
                break;
            case "用户":
                ManagementUser managementUser = userDAO.loginManagementUser(username, password);
                if (managementUser != null) {
                    HttpSession session = request.getSession();
                    session.setAttribute("managementUser", managementUser);
                    response.sendRedirect("management/index.jsp");
                } else {
                    request.setAttribute("error", "用户名或密码错误");
                    request.getRequestDispatcher("jsp/login.jsp").forward(request, response);
                }
                break;
            default:
                request.setAttribute("error", "请选择正确的角色");
                request.getRequestDispatcher("jsp/login.jsp").forward(request, response);
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 处理退出请求
        if (request.getParameter("logout") != null) {
            HttpSession session = request.getSession(false);
            if (session != null) {
                session.invalidate(); // 清除session中的所有数据
            }
            response.sendRedirect("jsp/login.jsp"); // 重定向到登录页面
            return;
        }

        request.getRequestDispatcher("jsp/login.jsp").forward(request, response);
    }
}